<template>
  <el-upload
      style="width: 100%"
      v-model:file-list="uploadFiles"
      :action="action"
      :headers="headers"
      multiple
      drag
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      :limit="limit"
      :on-exceed="handleExceed"
      :on-success="handleSuccess"
  >
    <el-icon class="el-icon--upload" color="var(--el-color-primary)"><upload-filled style="color: var(--el-color-primary)" /></el-icon>
    <div class="el-upload__text" style="color: var(--el-color-primary)">拖拽或选择文件上传</div>
    <template #tip>
      <div class="el-upload__tip">请上传小于 10MB 的文件</div>
    </template>
  </el-upload>

  <el-dialog v-model="previewVisible">
    <img w-full :src="previewUrl" alt="图片预览" />
  </el-dialog>
</template>

<script>
import {onMounted, reactive, toRefs} from 'vue'
import {Session} from '/@/utils/storage'
import { UploadFilled } from '@element-plus/icons-vue'
import {ElMessage} from 'element-plus';

export default {
  name: 'Upload',
  components: {
    UploadFilled
  },
  props: {
    limit: {
      default: 5,
      type: Number
    },
    /**
     * 文件url地址列表
     */
    fileList: {
      default: [],
      type: Array
    },
    fileNames: {
      default: [],
      typo: Array
    }
  },
  setup(props, context) {
    const {fileList} = toRefs(props)
    const {fileNames} = toRefs(props)
    const state = reactive({
      action: '/api/file/filaAttach/upload',
      uploadFiles: [],
      headers: {
        '17work': Session.get('token')
      },
      previewVisible: false,
      previewUrl: '',
    })

    /**
     * 上传超出限制
     */
    const handleExceed = (files, uploadFiles) => {
      ElMessage.warning('已达到最大上传文件数量！')
    }
    /**
     * 移除
     */
    const handleRemove = (file, files) => {
      // console.log('remove-file', file)
      // TODO 根据src（附件地址）删除服务器上的附件
      // let src = file.src
    }
    /**
     * 预览文件
     */
    const handlePreview = (file) => {
      state.previewUrl = file.src
      state.previewVisible = true
    }
    /**
     * 上传成功
     */
    const handleSuccess = (res, file, files) => {
      const {name, src} = res.data
      fileList.value.push(src)
      fileNames.value.push(name)
      file.src = src
      context.emit('update:fileList', fileList)
      context.emit('update:fileName', fileNames)
    }

    onMounted(() => {
      if (fileList.value && fileList.value.length > 0) {
        for (let i = 0; i < fileList.value.length; i++) {
          state.uploadFiles.push({
            uid: i,
            src: fileList.value[i],
            name: fileNames[i]
          })
        }
      }
    })

    return {
      ...toRefs(state),
      handleExceed,
      handleRemove,
      handlePreview,
      handleSuccess,
      fileList,
      fileNames
    }
  }
}
</script>

<style lang="scss" scoped>
  :deep(.el-upload-dragger) {
    padding-top: 10px !important;
    padding-bottom: 10px !important;
  }
</style>
